import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter/material.dart' hide ListTile, ButtonStyle, Colors;
import 'package:fnos_tv_desktop/core/api/bean/get_media_list_body.dart';
import 'package:fnos_tv_desktop/core/api/bean/media_list_result.dart';
import 'package:fnos_tv_desktop/core/model/media_databases.dart';
import 'package:provider/provider.dart';

import '../../../core/api/api.dart';
import '../../../core/api/bean/tags.dart';
import '../common/media_item.dart';
import '../main_page_model.dart';
import 'scroll_control.dart';

class MediaDbRow extends StatefulWidget {
  final MediaDatabase db;

  const MediaDbRow({super.key, required this.db});

  @override
  State<MediaDbRow> createState() => _MediaDbRowState();
}

class _MediaDbRowState extends State<MediaDbRow> {
  final scrollController = ScrollController();

  final api = Api();
  MediaListResult? result;

  get medias => result?.list;

  @override
  void initState() {
    refresh();
    super.initState();
  }

  @override
  void dispose() {
    scrollController.dispose();
    super.dispose();
  }

  void refresh() {
    api
        .getMediaList(
          GetMediaListBody(
            ancestorGuid: widget.db.guid,
            excludeGroupedVideo: 1,
            pageSize: 22,
            sortColumn: 'create_time',
            sortType: 'DESC',
            tags: Tags(type: ['Movie', 'TV', 'Directory', 'Video']),
          ),
        )
        .then((value) {
          if (mounted) {
            setState(() {
              result = value;
            });
          }
        });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ListTile(
          title: HyperlinkButton(
            style: ButtonStyle(
              foregroundColor: WidgetStateProperty.resolveWith((set) {
                return set.contains(WidgetState.hovered)
                    ? FluentTheme.of(context).accentColor
                    : FluentTheme.of(context).activeColor;
              }),
            ),
            onPressed: () {
              context.read<MainPageModel>().goToMediaDb(widget.db);
            },
            child: Text('${widget.db.title} >'),
          ),
        ),
        SizedBox(
          height: 276,
          child: ScrollControl(
            controller: scrollController,
            child: ListView.builder(
              controller: scrollController,
              shrinkWrap: true,
              padding: EdgeInsets.symmetric(horizontal: 12),
              scrollDirection: Axis.horizontal,
              itemCount: medias?.length ?? 0,
              itemBuilder: (context, index) {
                final media = medias[index];
                return MediaItem(info: media);
              },
            ),
          ),
        ),
      ],
    );
  }
}
